<!-- 系统参数 -->
<template>
  <div class="main-header">
    <el-card class="box-card" shadow="never">
      <div slot="header" class="cardHeard" style="height: 38px;">
        <div>
          <span class="title">系统全局参数</span>
        </div>
        <div>
          <el-button style="float: right; margin-left:5px;" type="primary"
            @click="confirmClick('systemForm')">保存设置</el-button>
        </div>
      </div>
      <div>
        <el-form :model="systemForm" :rules="rules" ref="systemForm" label-width="250px" style="margin-right:40px;">
          <el-row :gutter="24">
            <el-col :xs="12" :sm="12" :lg="12">
              <el-form-item label="根节点名称:" prop="root_corp_name" ref="root_corp_name"
                :rules="[{ required: true, message: '请输入根节点名称', trigger: 'blur' }]">
                <el-input size="small" v-model.trim="systemForm.root_corp_name" maxlength="64"
                  style="width:calc(100% - 20px);"></el-input>
              </el-form-item>
              <el-form-item label="开启SNMP服务:" prop="is_snmpd_open" ref="is_snmpd_open">
                <el-radio v-model="systemForm.is_snmpd_open" label="1">开启</el-radio>
                <el-radio v-model="systemForm.is_snmpd_open" label="0">关闭</el-radio>
              </el-form-item>
              <el-form-item label="客户端托盘显示控制:" prop="agent_show_trayicon" ref="agent_show_trayicon">
                <el-radio v-model="systemForm.agent_show_trayicon" :label="1">显示</el-radio>
                <el-radio v-model="systemForm.agent_show_trayicon" :label="0">隐藏</el-radio>
              </el-form-item>
              <el-form-item label="客户端托盘显示控制退出菜单:" prop="agent_show_trayicon_exit" ref="agent_show_trayicon_exit">
                <el-radio v-model="systemForm.agent_show_trayicon_exit" :label="1">显示</el-radio>
                <el-radio v-model="systemForm.agent_show_trayicon_exit" :label="0">隐藏</el-radio>
              </el-form-item>
              <el-form-item label="客户端托盘退出密码:" prop="agent_trayicon_exit_pwd" ref="agent_trayicon_exit_pwd">
                <el-input size="small" v-model.trim="systemForm.agent_trayicon_exit_pwd" maxlength="32"
                  style="width:calc(100% - 20px);"></el-input>
                <!-- <span style="color:#aaa">
                    （空表示不需要密码）
                  </span> -->
              </el-form-item>
              <el-form-item label="终端代理托盘提示内容:" prop="agent_trayicon_tip" ref="agent_trayicon_tip">
                <el-input size="small" v-model.trim="systemForm.agent_trayicon_tip" maxlength="20"
                  style="width:calc(100% - 20px);"></el-input>
              </el-form-item>
              <el-form-item label="" label-width="60px">
                <el-checkbox :true-label=1 :false-label=0
                  v-model="systemForm.is_check_eth0_switch">启用检测网口90秒内连续插拔超过3次，自动恢复地址为：</el-checkbox>
                <el-input size="small" v-model="systemForm.restore_ip" maxlength="64"
                  style="width:calc(100% - 405px);"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :lg="12">
              <el-form-item label="前端自动注销时长:" prop="ui_logout_interval" ref="ui_logout_interval">
                <el-input size="small" v-model.trim="systemForm.ui_logout_interval"
                  oninput="value=value.replace(/[^0-9]/g,'')" maxlength="9" style="width: 100%;"><span
                    slot="append">分钟</span></el-input>
              </el-form-item>
              <el-form-item label="非安装客户端资产超时离线时长:" prop="no_agent_offline_timeout" ref="no_agent_offline_timeout">
                <el-input size="small" v-model.trim="systemForm.no_agent_offline_timeout"
                  oninput="value=value.replace(/[^0-9]/g,'')" maxlength="9" style="width: 100%;"><span
                    slot="append">分钟</span></el-input>
              </el-form-item>
              <el-form-item label="连续运行多长时间自动重启设备:" prop="reset_keep_run_seconds" ref="reset_keep_run_seconds">
                <el-input size="small" v-model.trim="systemForm.reset_keep_run_seconds"
                  oninput="value=value.replace(/[^0-9]/g,'')" maxlength="3" style="width: 100%;"><span
                    slot="append">天</span></el-input>
              </el-form-item>
              <el-form-item label="每天指定时间自动重启设备:" prop="reset_on_hours" ref="reset_on_hours">
                <el-select size="small" v-model="systemForm.reset_on_hours" style="width: 100%;">
                  <el-option label="不执行定点自动重启" :value="0"></el-option>
                  <el-option v-for="item in 23" :key="item" :label="item + ':00'" :value="item"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="首页数据展示天数:" prop="home_page_data_days" ref="home_page_data_days">
                <el-select v-model="systemForm.home_page_data_days" placeholder="请选择天数" size="small" style="width: 100%;">
                  <el-option v-for="day in 10" :key="day" :label="`${day} 天`" :value="day" />
                </el-select>
              </el-form-item>
              <el-form-item label="字典同步间隔:" prop="center_sync_param_interval" ref="center_sync_param_interval">
                <el-input size="small" v-model.trim="systemForm.center_sync_param_interval"
                  oninput="value=value.replace(/[^0-9]/g,'')" maxlength="9" style="width: 100%;"><span
                    slot="append">分钟</span></el-input>
              </el-form-item>
              <el-form-item label="病毒检测引擎:" prop="scan_file_virus_mode" ref="scan_file_virus_mode">
                <el-select size="small" v-model="systemForm.scan_file_virus_mode" style="width:calc(100% - 90px);">
                  <el-option v-for="(item, index) in virusList" :key="index" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
                <el-button type="primary" size="small" @click="RestartAntiVirus"
                  style="margin-left: 10px;">立刻生效</el-button>
              </el-form-item>
              <el-form-item label="病毒文件处理策略:" prop="forbid_run_virus_file" ref="forbid_run_virus_file">
                <el-radio v-model="systemForm.forbid_run_virus_file" label="0">允许运行</el-radio>
                <el-radio v-model="systemForm.forbid_run_virus_file" label="1">禁止运行</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { connrequest } from '@/api/firstPage';
export default {
  data() {
    return {
      systemForm: {},
      oldData: [],
      rules: {},
      virusList: [
        { label: '国际病毒检测引擎', value: 3 },
        { label: '国产病毒检测引擎', value: 2 },
        { label: '开源病毒检测引擎', value: 1 },
        { label: '多检测引擎（严格）', value: 5 },
        { label: '多检测引擎（宽松）', value: 4 },
        { label: '不做病毒检测（所有文件更新为无病毒）', value: 6 },
      ]
    }
  },
  created() {
    this.getData();
  },
  methods: {
    // 获取系统参数数据
    async getData() {
      const res = await connrequest('GetThresholdConfig');
      if (res.Status.StatusCode !== 0) return;
      const dataList = res.Data || [];
      this.oldData = dataList;
      // 将数组转为对象格式：{ Name: Value }
      const rawForm = {};
      dataList.forEach(item => {
        rawForm[item.Name] = item.Value;
      });
      // 需要进行单位转换的字段（从秒 → 分钟、天）
      const unitDivideMap = {
        reset_keep_run_seconds: 24 * 3600, // 秒 → 天
        no_agent_offline_timeout: 60,      // 秒 → 分钟
        center_sync_param_interval: 60,    // 秒 → 分钟
        ui_logout_interval: 60             // 秒 → 分钟
      };
      // 构建最终用于表单显示的 systemForm
      this.systemForm = Object.keys(rawForm).reduce((acc, key) => {
        const value = rawForm[key];
        // 若该字段需要单位转换，则执行除法，否则直接赋值
        acc[key] = unitDivideMap[key] ? value / unitDivideMap[key] : value;
        return acc;
      }, {});
    },
    async RestartAntiVirus() {
      const res = await connrequest('RestartAntiVirus')
      if (res.Status.StatusCode === 0) {
        this.confirmClick('systemForm')
        this.$message.success('病毒检测引擎已经生效')
      }
    },
    // 提交系统参数配置
    async confirmClick(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 字段中文描述映射（用于构建 Descp 字段）
          const fieldDescpMap = {
            is_snmpd_open: '开启SNMP服务',
            agent_show_trayicon: '客户端托盘显示控制',
            agent_show_trayicon_exit: '客户端托盘显示控制退出菜单',
            agent_trayicon_exit_pwd: '客户端托盘退出密码',
            root_corp_name: '根节点名称',
            agent_trayicon_tip: '终端代理托盘提示内容',
            ui_logout_interval: '前端自动注销时长',
            no_agent_offline_timeout: '非安装客户端资产超时离线时长',
            reset_keep_run_seconds: '连续运行多长时间自动重启设备',
            is_check_eth0_switch: '启动网口连续插拔检测',
            restore_ip: '网口地址恢复为',
            scan_file_virus_mode: '病毒检测引擎',
            forbid_run_virus_file: '病毒文件处理策略',
            center_sync_param_interval: '字典同步间隔',
            home_page_data_days: ''
          };
          // 需要进行单位转换的字段及其换算倍数（统一转为秒）
          const unitConversionMap = {
            reset_keep_run_seconds: 24 * 3600, // 天 → 秒
            no_agent_offline_timeout: 60,      // 分钟 → 秒
            center_sync_param_interval: 60,    // 分钟 → 秒
            ui_logout_interval: 60             // 分钟 → 秒
          };
          // 构造最终提交参数数组
          const formArray = Object.keys(this.systemForm).map(key => {
            // 原始值
            const rawValue = this.systemForm[key];
            // 单位转换
            const convertedValue = unitConversionMap[key] ? rawValue * unitConversionMap[key] : rawValue;
            // 获取字段描述，优先取固定映射，没有则从 oldData 中找
            const descp = fieldDescpMap[key] || this.oldData?.find(item => item.Name === key)?.Descp || '';
            return {
              Name: key,
              Value: convertedValue,
              Descp: descp
            };
          });
          const paramData = {
            Data: formArray,
          };
          const res = await connrequest('SetThresholdConfig', paramData);
          if (res.Status.StatusCode === 0) {
            this.$message.success('更改成功');
            this.getData();
            this.$emit('changeData', 'System');
          }
        } else {
          return false;
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.text {
  font-size: 14px;
}

.box-card {
  // margin: 16px;
  margin-bottom: 0px !important;
}

.cardHeard {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

::v-deep .el-card__header {
  padding: 10px !important;
}

.el-form-item {
  margin-bottom: 10px !important;
}

::v-deep .el-form-item__error {
  padding-top: 0 !important;
}
</style>